/*
 * @Description: 权限规则 - 用户列表 - 操作组件
 * @Author: Rfan
 * @Date: 2022-04-06 14:07:46
 * @LastEditTime: 2022-05-25 08:58:12
 */

import { useMemo, useState } from 'react';
import { Button, Space, Typography } from 'antd';
import classNames from 'classnames/bind';
import { useManageRuleContext } from '../../contexts/ManageRuleContext';
import AddUserDialog from '../dialogs/AddUser/Index';

import styles from '../../styles/list.module.scss';

const cx = classNames.bind(styles);

const UserOperate = () => {
  const { ruleSelectItems, userSelectItems, userList, updateSpecUserList, deleteSpecUser } =
    useManageRuleContext();
  // 添加用户弹窗状态
  const [addUserVisible, setAddUserVisible] = useState(false);
  // 添加用户弹窗状态
  const [tabType, setTabType] = useState(0);
  const deleteUser = () => {
    deleteSpecUser(userSelectItems);
  };

  /**
   * @description: 打开添加弹窗
   * @param {number} id
   * @return {*}
   */
  const showAddDialog = (id: number) => {
    setTabType(id);
    setAddUserVisible(true);
  };

  /**
   * @description: 关闭添加用户弹窗，根据参数判断取消还是保存
   * @param {any} data 添加的用户，保存时使用
   */
  const closeAddDialog = (data: any) => {
    if (data && data.entryList && data.operateRightsColList) {
      const _list = [...userList, ...data.entryList];
      data.entryList = _list;
      updateSpecUserList(data);
    }
    setAddUserVisible(false);
  };

  return (
    <>
      <div className="filter-container">
        <p className={cx('page-title')}>
          所使用的用户和组{' '}
          <Typography.Text type="secondary"> 只列出当前规则直接作用于的组织和用户</Typography.Text>
        </p>
        <Space size="small">
          <Button
            disabled={userSelectItems.length <= 0}
            onClick={() => {
              deleteUser();
            }}
          >
            删除用户或组
          </Button>
          <Button
            disabled={ruleSelectItems.length <= 0}
            onClick={() => {
              showAddDialog(1);
            }}
          >
            添加组
          </Button>
          <Button
            disabled={ruleSelectItems.length <= 0}
            onClick={() => {
              showAddDialog(0);
            }}
          >
            添加用户
          </Button>
        </Space>
      </div>
      {useMemo(
        () => (
          <AddUserDialog
            visible={addUserVisible}
            ruleId={ruleSelectItems[0]}
            tabType={tabType}
            onClose={closeAddDialog}
          />
        ),
        [ruleSelectItems, addUserVisible, tabType]
      )}
    </>
  );
};

export default UserOperate;
